package com.shanghaionstar.remote;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.onstar.cn.auth.userProfile.FeatureEnum;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.response.AuthorizedSubscriberResponse;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.VehicleLoadingActivity;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.activity.webview.handler.WebDataEntity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.iview.ILoginListener;
import com.shanghaionstar.remote.iview.IRemoteView;
import com.shanghaionstar.remote.manager.RemoteOperateManager;
import com.shanghaionstar.remote.model.RemoteModel;
import com.shanghaionstar.remote.presenter.RemotePresenter;
import com.shanghaionstar.remote.share.ShareRemoteActivity;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.JoinMeConstants;
import com.shanghaionstar.utils.LoginUtil;
import com.shanghaionstar.weight.TopLayout;

import rx.Subscription;

/**
 * Created by 6335yz on 2016/6/21.
 */
public class RemoteFragment extends BaseFragment implements View.OnClickListener, IRemoteView, ILoginListener {

    @FindViewById
    TopLayout top_layout;

    @FindViewById
    ImageButton unlock, lock, start, stop, alert;
    @FindViewById
    private TextView remote_notification_hint, remote_notification_time;

    private RemotePresenter remotePresenter;
    @FindViewById
    private View start_stop_layout;
    @FindViewById
    private RelativeLayout one_layout;

    private ImageButton[] btns;
    private TextView mRemoteShareTv;

    @Override
    public int getLayoutId() {
        return R.layout.tab_fragment_remote;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        /**
         * 供多个页面使用
         */
        if (getArguments() != null) {
            isNeedTitle(getArguments().getBoolean("isNeedTitle", true));
        }
        if (isFirstLoad()) {
            remotePresenter = new RemotePresenter(baseActivity.getScheduler(), baseActivity);
            remotePresenter.setView(this);
            remotePresenter.registLoginAndOutShowView();
//            pinCallBack();
            /**
             * 默认显示远程启停操作
             */
            showStartOrNot(BusinessUtil.isServiceFeature(FeatureEnum.START.value(), baseActivity));

            //使用须知
            top_layout.setOnRightTextClickLstener(getString(R.string.h5_intruction), new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    WebDataEntity entity = new WebDataEntity();
                    entity.setTopTitle(getString(R.string.h5_intruction));
                    entity.setLinkUrl(Constants.CURRENT_PREFIX_H5_URL + Constants.REMOTEUSERHELP_ZH);
                    CommonWebViewActivity.launchCommonWeb(getActivity(), entity);
//                    Intent intent = new Intent(getActivity(), CommonWebViewActivity.class);
//                    intent.putExtra("topTitle", getString(R.string.h5_intruction));
//                    intent.putExtra("linkUrl", EncryptUtil.decryptBase64(getActivity(), Constants.PREFIX_H5_URL) + Constants.REMOTEUSERHELP_ZH);
//                    startActivity(intent);
                }
            });
            //顺序不能变，便于快捷键操作
            btns = new ImageButton[]{start, stop, lock, unlock, alert};
        }
    }

    private void initRemoteShare() {
        mRemoteShareTv = top_layout.getClose();
        mRemoteShareTv.setVisibility(View.VISIBLE);
        mRemoteShareTv.setText(R.string.remote_share);
        mRemoteShareTv.setTextColor(getResources().getColor(R.color.color_007aff));
        mRemoteShareTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(getActivity(), ShareRemoteActivity.class);
                getActivity().startActivity(it);
            }
        });
    }


    public void onPageSelected() {
        showStartOrNot(BusinessUtil.isServiceFeature(FeatureEnum.START.value(), baseActivity));
        String role = ApplicationUtil.getInstance().getLoginRole();
        if (role.equalsIgnoreCase(Constants.OWNER)) {
            initRemoteShare();
            return;
        }
        if (!TextUtils.isEmpty(role) && !role.equalsIgnoreCase(Constants.OWNER) && !role.equalsIgnoreCase(Constants.VISITOR)) {
            mRemoteShareTv = top_layout.getClose();
            mRemoteShareTv.setVisibility(View.GONE);
            if (ApplicationUtil.getInstance().isAuthorized()) {
                new ToastView(baseActivity).showAuthorizedToast(R.color.color_64c6fd, R.string.remote_share_tip_status, R.string.remote_share_tips);
            } else {
                new ToastView(baseActivity).showUnAuthorizedToast(R.color.color_fc7a7a, R.string.remote_share_tip_unauthorized);
            }
        }
    }

    public void remotePerform(int i) {
        btns[i].performClick();
    }


    @Override
    public void onResume() {
        super.onResume();
        if (ApplicationUtil.getInstance().isLogin())
            showStartOrNot(BusinessUtil.isServiceFeature(FeatureEnum.START.value(), baseActivity)
                    || JoinMeConstants.VISITOR.equalsIgnoreCase(ApplicationUtil.getInstance().getLoginRole()));
        else
            showStartOrNot(true);
    }

    public void isNeedTitle(boolean isNeed) {
        top_layout.setVisibility(isNeed ? View.VISIBLE : View.GONE);
        if (isNeed) {
            top_layout.setOnRightClickListener(getString(R.string.remote_use_guide), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    log.d("need title");
                }
            });
        }
    }

    private Subscription remotePageSubscription;

    @Override
    public void pinCallBack() {
        /**
         * 从pin码页面返回
         */
//        remotePageSubscription = RxBus.getDefault().toObserverable(RxConstants.REMOTE_PAGE, PinModel.class).filter(new Func1<PinModel, Boolean>() {
//            @Override
//            public Boolean call(PinModel pinModel) {
//                return pinModel.isPinSuccess();
//            }
//        }).subscribeOn(new AppScheduler().backgroundThread())
//                .observeOn(new AppScheduler().mainThread()).subscribe(new Action1<PinModel>() {
//                    @Override
//                    public void call(PinModel pinModel) {
//                        RemoteModel remoteModel = new RemoteModel.Builder()
//                                .setRemoteCommandsType(pinModel.getRemoteCommandsType())
//                                .setFlash(pinModel.isFlash()).setHorn(pinModel.isHorn())
//                                .create();
//                        remotePresenter.commandByType(remoteModel);
//                    }
//                });
    }

    private ReportReqParam getRemoteCommandReportParams(String functionId) {
        ReportReqParam reportReqParam = new ReportReqParam.ReportReqParamBuilder().channelId("0")
                .deviceType("0")
                .functionNameFindId(functionId)
                .objectID("")
                .objectType("9")
                .operationType("")
                .result("0")
                .type("0").createReportReqParam();
        return reportReqParam;
    }

    @OnClick({R.id.unlock, R.id.lock, R.id.start, R.id.stop, R.id.alert})
    @Override
    public void onClick(View v) {
        clickView = v;
        boolean isLogin = ApplicationUtil.getInstance().isLogin();
        if (!isLogin) {
            onAuthorizedClick(v);
        } else {
            String role = ApplicationUtil.getInstance().getLoginRole();
            boolean isOwner = role.equalsIgnoreCase(Constants.OWNER);
            boolean isVisitor = role.equalsIgnoreCase(Constants.VISITOR);
            if (isOwner || isVisitor) {
                onAuthorizedClick(v);
            } else {
                remotePresenter.getAuthorizedStatus();
            }
        }

    }

    private View clickView;

    private void onAuthorizedClick(View v) {
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.unlock:
                BusinessUtil.sendReportByRequestParams(getContext(), FunctionNameFindId.Remote_DoorUnlock.getStringValue(),
                        getRemoteCommandReportParams(FunctionNameFindId.Remote_DoorUnlock.getStringValue()));
                bundle.putSerializable("commands", RemoteCommandsType.COMMANDS_UNLOCK_DOOR);
                break;
            case R.id.lock:
                BusinessUtil.sendReportByRequestParams(getContext(), FunctionNameFindId.Remote_DoorLock.getStringValue(),
                        getRemoteCommandReportParams(FunctionNameFindId.Remote_DoorLock.getStringValue()));
                bundle.putSerializable("commands", RemoteCommandsType.COMMANDS_LOCK_DOOR);
                break;
            case R.id.start:
                BusinessUtil.sendReportByRequestParams(getContext(), FunctionNameFindId.Remote_Start.getStringValue(),
                        getRemoteCommandReportParams(FunctionNameFindId.Remote_Start.getStringValue()));
                bundle.putSerializable("commands", RemoteCommandsType.COMMANDS_START);
                BusinessUtil.sendReportByClickType(getContext(), FunctionNameFindId.Remote_Start.getStringValue());
                break;
            case R.id.stop:
                BusinessUtil.sendReportByRequestParams(getContext(), FunctionNameFindId.Remote_CancelStart.getStringValue(),
                        getRemoteCommandReportParams(FunctionNameFindId.Remote_CancelStart.getStringValue()));
                bundle.putSerializable("commands", RemoteCommandsType.COMMANDS_CANCEL_START);
                break;
            case R.id.alert:
                BusinessUtil.sendReportByRequestParams(getContext(), FunctionNameFindId.Remote_HornsLights.getStringValue(),
                        getRemoteCommandReportParams(FunctionNameFindId.Remote_HornsLights.getStringValue()));
                bundle.putSerializable("commands", RemoteCommandsType.COMMANDS_ALERT);
                break;
        }
        new LoginUtil().loginAndActionCallBack(baseActivity, RxConstants.REMOTE_PAGE, this, bundle);
    }

    @Override
    public void showCoverImage(boolean isShow) {

    }

    @Override
    public void showLoadingAnimation(String commandType) {

    }

    @Override
    public void hideLoadingAnimation() {

    }

    @Override
    public void showCommandResult(boolean isShow, String hint, String time) {
        remote_notification_hint.setVisibility(isShow ? View.VISIBLE : View.GONE);
        remote_notification_hint.setText(hint);
        remote_notification_time.setText(time);
    }

    @Override
    public void setLoading(boolean isLoading) {

    }

    @Override
    public void onResponseError(OnStarException e) {
//        AlertDialogUtil.showAlertDialog(baseActivity, getString(R.string.dialog_warning), e.getMessage());
        AlertDialogUtil.showDialogByOnstarException(onActivity(), e);
    }

    @Override
    public void onReponseSuccess(final RemoteModel model) {
        switch (model.getCommandStatus()) {
            case START:
                AlertDialogUtil.showAlertDialog(baseActivity, getString(R.string.dialog_warning),
                    model.getAlertMsg(), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            RemoteOperateManager.getInstance().init(getActivity())
                                    .exeRemote(model.getRemoteCommandsType());
//                            remotePresenter.showPinOrNot(getFragmentManager(), model);
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                break;
            case LOADING:
                setLoading(true);
                break;
            case FINISH:
                AlertDialogUtil.showAlertDialog(baseActivity, getString(R.string.dialog_warning),
                        model.getAlertMsg());
                break;
        }
    }

    @Override
    public Activity onActivity() {
        return getActivity();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (remotePresenter != null) {
            remotePresenter.unRegisterSubscriber();
            remotePresenter = null;
        }
        if (remotePageSubscription != null && !remotePageSubscription.isUnsubscribed()) {
            remotePageSubscription.unsubscribe();
            remotePageSubscription = null;
        }
    }

    @Override
    public void showToast(String msg) {
//        new ToastView(baseActivity).showRemoteToast(msg);
    }

    @Override
    public void showStartOrNot(boolean isShow) {
        start_stop_layout.setVisibility(isShow ? View.VISIBLE : View.GONE);
        one_layout.setVisibility(isShow ? View.GONE : View.VISIBLE);
    }

    @Override
    public void onLogin(Bundle bundle, String resultCode) {
        if (bundle != null) {
            if (RxConstants.ACTION_SUCCESS.equals(resultCode)) {
                RemoteCommandsType remoteCommandsType = (RemoteCommandsType) bundle.getSerializable("commands");
                remotePresenter.doCommand(remoteCommandsType);
            }
        }
    }

    public static RemoteFragment newInstance(boolean isNeedTitle) {
        Bundle bundle = new Bundle();
        RemoteFragment remoteFragment = new RemoteFragment();
        bundle.putSerializable("isNeedTitle", isNeedTitle);
        remoteFragment.setArguments(bundle);
        return remoteFragment;
    }

    @Override
    public void showCommandLoading(boolean isShow) {
        if (isShow) {
            startActivity(new Intent(baseActivity, VehicleLoadingActivity.class));
        }
    }

    @Override
    public void showAuthorizeStatus(AuthorizedSubscriberResponse response) {
        String status = response.getAuthorizeStatus();
        boolean isAuthorized = !TextUtils.isEmpty(status) && status.equalsIgnoreCase("1");
        ApplicationUtil.getInstance().setAuthorized(isAuthorized);
        if (isAuthorized) {
            if (clickView != null) {
                onAuthorizedClick(clickView);
            }
        }else{
            new ToastView(baseActivity).showUnAuthorizedToast(R.color.color_fc7a7a, R.string.remote_share_tip_unauthorized);
            if (clickView != null) {
                onAuthorizedClick(clickView);
            }
        }

    }

}
